From Cppreference
|
|
|
|
|
|
|
| template< bool B, class T = void > struct enable_if;
|
|
(C++11 feature)
|
|
|
|
If B is true, std::enable_if has a public member typedef type, equal to T; otherwise, there is no member typedef. This metafunction is used to conditionally remove functions and classes from overload resolution based on type traits and to provide separate function overloads and specializations for different type traits. std:enable_if can be used as an additional function argument (the only option for constructors and destructors), as a return type (the only option for operators), or as a class template parameter.
[edit] Member types
|
|
| Type
|
Definition
|
|
|
| type
|
either T or no such member, depending on the value of B
|
[edit] Equivalent definition
template<bool B, class T = void>
struct enable_if {};
template<class T>
struct enable_if<true, T> { typedef T type; };
|
[edit] Example
#include <type_traits>
#include <iostream>
// the function foo1 has different overloads for floating-point types
// and for integral types. It uses std::enable_if as the return type.
template<class T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type foo1(T t) {
std::cout << "floating-point overload of foo1() called\n";
return t;
}
template<class T>
typename std::enable_if<std::is_integral<T>::value, T>::type foo1(T t) {
std::cout << "integral overload of foo1() called\n";
return t;
}
// the function foo2 is only defined for integer T, illustrating the use of
// enable_if as a function argument.
template<class T>
T foo2(T t, typename std::enable_if<std::is_integral<T>::value >::type* = 0) {
return t;
}
// the class template A is specialized for floating-point T
template<class T, class Enable = void>
class A; // undefined
template<class T>
class A<T, typename std::enable_if<std::is_floating_point<T>::value >::type> {
};
int main()
{
foo1(1.2); // OK, calls the first version of foo1()
foo1(10); // OK, calls the second version of foo1()
// foo2(0.1); // compile-time error
foo2(7); // Ok
// A<int> a1; // compile-time error
A<double> a1; // OK
}
Output:
floating-point overload of foo1() called
integral overload of foo1() called
[edit] See also